let ___systemIsCb = false;
let ___locationdata = [];

function changeClocationSelect(o, index) {

	var select_plocation = document.getElementById("select_plocation");
	var select_clocation = document.getElementById("select_clocation");
	//清空上次的选项
	select_clocation.options.length = 0;
	//获取省一级的下拉列表选中的索引
	//var index=select_plocation.selectedIndex;

	//console.log(index);
	//console.log(___locationdata[index]);
	for (var i = 0; i < ___locationdata[index]['_childs'].length; i++) {
		select_clocation.options[i] = new Option(___locationdata[index]['_childs'][i]['name'], ___locationdata[index][
			'_childs'
		][i]['id']);
	}
}

function initBaseData() {

	VisualReq.loadLocationData({}, function(data) {
		if (data && data['list']) {
			var select_plocation = document.getElementById("select_plocation");
			//清空上次的选项
			select_plocation.options.length = 0;
			___locationdata = data['list'];
			for (var i = 0; i < ___locationdata.length; i++) {
				select_plocation.options[i] = new Option(___locationdata[i]['name'], ___locationdata[i]['id']);
			}

			changeClocationSelect(null, 0);
		}
	});
}

//初始化部门组织树
function initDepartSelect(){
	var zNodes = [];
	VisualReq.initDepartSelect({},function(info){
		logger.log(info);
			if(info["code"] == 0){
				$("#verify-form").hide();
				$("#regdevice_form").show();
				zNodes = info["data"];
				var defaults = {

					zNodes: zNodes,
					height: 233,
					filter: true,
					searchShowParent: true,
					chkStyle: "radio"
				};
				var selectObj = $("#depart").treeSelect(defaults);
				$("#submitDeviceInfo").click(function () {

					var data = $("#regdevice_form").serializeJson();

					data['locationId'] = selectObj.val()[0];
					updateClientInfo(data);

				})
			}else{
				$("#verify-form").show();
				$("#regdevice_form").hide();
				Qmsg.error(info["msg"]);
			}
	})

}


function showSetServerInfo(){
	//初始化表单
	var data = VisualConst.getServerInfo();
	data["port"] = data["port"] || VisualConst.getAppCfg()["ws"]["ws_port"];
	
	// console.log("VisualConst.getAppCfg",VisualConst.getAppCfg());
	$("#verify-form").find(':input').each(function() {
		$(this).val(data[$(this).attr('name')]);
	});
	//显示表单界面
	document.getElementById("client_location").style.display = "block";
}
function hideSetServerInfo(){
	document.getElementById("client_location").style.display = "none";
}
function cancelSetServerInfo(){
	hideSetServerInfo();
	$("#verify-form")[0].reset();
}
function submitSetServerInfo(){
	var formJSon = $("#verify-form").serializeJson();
	logger.info(formJSon);

	if(null == formJSon['ip'] || '' == formJSon['ip']){
		Qmsg.error('请填写服务器IP');
		return false;
	}
	if(null == formJSon['port'] || '' == formJSon['port']){
		Qmsg.error('请填写服务器PORT');
		return false;
	}

	//formJSon['sysinfo'] = JSON.stringify(____clientStaticData);

	var device = VisualConst.getCustomDevice(____clientStaticData["system"])

	formJSon["id"] = device["deviceid"];
	formJSon["deviceid"] = device["deviceid"];
	formJSon["appid"] = VisualConst.getAppCfg()['comm']['appid'];

	//保存配置信息到配置文件
	VisualConst.setServerInfo(formJSon);
	//刷新首页
	window.location.reload();
}
//验证租户代码和密码
function submitVerifyInfo(){
	var formJSon = $("#verify-form").serializeJson();
	logger.info(formJSon);

	if(null == formJSon['subdomain'] || '' == formJSon['subdomain']){
		Qmsg.error('企业代码不能为空!');
		return false;
	}

	formJSon['sysinfo'] = JSON.stringify(____clientStaticData);

	var device = VisualConst.getCustomDevice(____clientStaticData["system"])

	formJSon["id"] = device["deviceid"];
	formJSon["deviceid"] = device["deviceid"];
	formJSon["appid"] = VisualConst.getAppCfg()['comm']['appid'];
	VisualReq.clientLogin(formJSon,function(info){
		logger.info(info);
		if(info["code"] == 0){
			var tenantId = info["data"]["id"] + '';

			//租户id写入文件
			Lib.setStorage('_tenantId',tenantId);
			Lib.setStorage('_token',info['token']);
			Lib.setStorage('_deviceId',device["deviceid"]);

			//刷新request.header
			VisualReq.reloadRequests();
			initDepartSelect();
			$("#tenantName").html(info["data"]["name"]);
			Qmsg.success("登陆成功,请选择设备所属部门!");
		}else{
			Qmsg.error(info["msg"]);
		}

	})
}

/**
 * 多租户版本，绑定设备信息，绑定租户下部门
 *
 * */
function updateClientInfo(data) {
	var device = VisualConst.getCustomDevice(____clientStaticData["system"])
	data["id"] = device["deviceid"];
	VisualReq.updateClientInfo(
		data,
		function(result) {
			//console.log(result);
			if (result["code"] == 0) {
				//绑定成功
				Qmsg.success("绑定成功");

				document.getElementById("client_location").style.display = "none";
				loadClientInfo();
			} else {
				//console.log(result);
			}
		}
	);
}


function checkUpdate() {
	//alert(____VP_CODE);
	var param = {
		"apihost": ____apihost,
		"pvcode": ____VP_CODE,
		"vcode": "",
		"sysinfo": JSON.stringify(____clientStaticData),
		"appid": VisualConst.getAppCfg()['comm']['appid']
	};
	//console.log("checkUpdate---------" + ____VP_CODE);
	ipcRenderer.send('app-checkUpdate', JSON.stringify(param));
}

function loadClientInfo() {
	var serverInfo = VisualConst.getServerInfo();
	VisualReq.loadClientInfo(
		JSON.stringify(VisualConst.getCustomDevice(____clientStaticData["system"])),
		function(info) {
			Cloading.hide();
			//token验证失败
			if(info["code"] == -999){
				document.getElementById("client_location").style.display = "block";
				setStatusText(info["msg"]);
				Qmsg.success(info["msg"]);
				return false;
			}


			_appConfig = info["appConfig"];
			var sys_status = "";

			if (info["code"] == 1000) {
				//无绑定
				sys_status += "未注册设备位置信息";
				document.getElementById("client_location").style.display = "block";
			} else if (info["code"] == 0) {
				//有绑定
				//隐藏 位置设定
				document.getElementById("client_location").style.display = "none";
				if (info["data"]["device"]) {
					//将设备信息临时缓存
					____clientDeviceInfo = info["data"]["device"];
					//设置状态信息
					if(info["isServer"]==true){
						sys_status += "已连接 <a>" + (serverInfo["ip"] || "") + "</a>";
						sys_status += "<br>设备ID：" + (info["data"]["device"]["id"] || '') ;
						sys_status += "<br>设备IP：" + (____clientStaticData["network"]["address"] || '') ;
					}else{
						sys_status += "已连接，" + info["data"]["device"]["locationName"] + "_" + (info["data"]["device"]["locationRemark"] || '')
					}
				}

				var contentMsg = {};
				//读取本地缓存，展示上次推送的内容
				contentMsg = VisualConst.getLastContent();
				
				//未获取到本地缓存的内容
				if (  !contentMsg["contentlist"] || (contentMsg["contentlist"] && contentMsg["contentlist"].length==0)) {
					//获取官方示例
					pushLoadContentPage(contentMsg);
					VisualReq.loadExmple(function(body){
						//console.log("body",body) // 输出网页内容
						contentMsg = {
							"pushtype": 'screens',
							"contentlist": body["data"]
						};
						// pushLoadContentPage(contentMsg);
					})
				}else{
					contentMsg["clientsetup"] = info["data"]["clientsetup"];
					contentMsg["extparam"] = info["data"]["extparam"];
					pushLoadContentPage(contentMsg);
				}
			} else {
				//异常了
				sys_status += "未连接服务器";
			}

			setStatusText(sys_status);
		}
	);
}

function reConnectOpen() {
	Cloading.show();
	//initBaseData();
	loadClientInfo();
}

function loadMainPage() {
	Cloading.show();
	//获取客户端的设备信息,性能需要优化
	VisualConst.getClientStaticData(function(data) {
		Cloading.hide();
		if (___systemIsCb) {
		} else {
			___systemIsCb = true;
		}
		// console.log(data);
		connectWsServer(); //链接服务
	});
	//网络断开和连上的状态监听（只是监听有没有插网线或者有没有连到wifi，不能确定是否可以连接到应用服务器）
	window.addEventListener('online', alertOnlineStatus)
	window.addEventListener('offline', alertOnlineStatus)
	alertOnlineStatus();
}

//版本更新请求地址         
var isManualUpdate = false;
ipcRenderer.removeAllListeners();
ipcRenderer.on('app-ioHookEventHandler', (event, arg) => {
	if(arg["t"] == 'mousemove'){
	}else{
		console.log("app-ioHookEventHandler",arg) // prints "pong"
	}
})
ipcRenderer.on('app-pushmessage', (event, arg) => {
	//console.log(arg) // prints "pong"
})
ipcRenderer.on('updaterMessage', (event, arg) => {
	if(arg.code==1003){
		arg.msg = "当前为最新版本";
	}
	document.getElementById("update_info").innerHTML = arg.msg;
});

function updateClientNow() {
	ipcRenderer.send('isUpdateNow', {});
}

ipcRenderer.on('isUpdateNow', (event, arg) => {
	document.getElementById("update_info").innerHTML = "<a onclick='updateClientNow()'>新版本已下载完成，点击立即安装</a>";
});

ipcRenderer.on('updaterDownloadProgress', (event, arg) => {
	//console.log("updaterDownloadProgress",event,arg);
	if(arg.percent){
		//正在下载更新 percent arg.percent.toFixed(2)
		$("#index_checkupdate").html("&nbsp;&nbsp;正在下载新版本" + arg.percent.toFixed(2) + "%");
	}
});

function checkUpdate() {
	// console.log("checkUpdate==========",VisualConst.getAppCfg()["comm"]["updateFeedUrl"]);
	logger.log("checkUpdate==========",VisualConst.getAppCfg()["comm"]["updateFeedUrl"])
	ipcRenderer.send('update', { "feedUrl": VisualConst.getAppCfg()["comm"]["updateFeedUrl"]});
}
//checkUpdate();//自动检查更新
// $("#index_checkupdate").on("click", function () {
// 	isManualUpdate = true;//手动更新
// 	checkUpdate();
// });

